package com.example.demo.hotload.spring;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class ClassLoadUtil {

    public static Class<?> loadClass(String classPath, String className) {
        MyClassLoader loader = new MyClassLoader(classPath);
        return loader.findClass(className);
    }

    private static class MyClassLoader extends ClassLoader {
        /**
         * 需要加载类的路径，E:\Hello.class
         */
        private final String classPath;

        public MyClassLoader(String classPath) {
            super();
            this.classPath = classPath;
        }

        @Override
        protected Class<?> findClass(String className) {
            Class<?> clazz = null;
            // 获取class文件字节码数组
            byte[] clazzByteArr = getData();
            if (clazzByteArr != null) {
                // 将class的字节码数组转换成class类的实例
                clazz = defineClass(className, clazzByteArr, 0, clazzByteArr.length);
            }
            return clazz;
        }

        /**
         * 获取class文件字节数组
         * @return 字节码
         */
        private byte[] getData() {
            File file = new File(this.classPath);
            if (file.exists()) {
                try (FileInputStream in = new FileInputStream(file)) {
                    return IOUtils.toByteArray(in);
                } catch (IOException e) {
                    log.error("读取文件异常：", e);
                }
            }
            return null;
        }
    }
}